package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.utils.thread.WeMediaThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * @author 陈辉
 * @data 2023 14:37
 */
@Service
@Transactional
@Slf4j
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FileStorageService fileStorageService;

    /**
     * 上传素材图片
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult upload(MultipartFile multipartFile) {
        //1. 参数校验
        if (multipartFile == null)
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);

        //2. 数据处理
        //2.1 处理文件名
        String fileName = UUID.randomUUID().toString();
        //2.2 获取原始文件的后缀名   "a.a.png"
        String originalFilename = multipartFile.getOriginalFilename();
        String postfix = originalFilename.substring(originalFilename.lastIndexOf("."));

        //3. 将图片上传到minIO
        try {
            String url = fileStorageService.uploadImgFile("", fileName + postfix, multipartFile.getInputStream());
            //4. 封装素材实体对象，并存入数据库表：wm_material
            WmMaterial material = WmMaterial.builder()
                    .url(url)
                    .userId(WeMediaThreadLocalUtil.get())
                    .type((short)0)
                    .isCollection((short)0)
                    .createdTime(new Date())
                    .build();

            save(material);

            //5. 将wm_material返回给前端
            return ResponseResult.okResult(material);

        } catch (IOException e) {
            e.printStackTrace();
        }


        return null;
    }

    /**
     * 素材列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        //1. 检查参数
        if (dto == null)
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        dto.checkParam();

        //2. 组装分页条件查询构造器
        Page page = new Page(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<WmMaterial> wrapper = Wrappers.<WmMaterial>lambdaQuery()
                .eq(WmMaterial::getUserId, WeMediaThreadLocalUtil.get())
                .eq(WmMaterial::getIsCollection,dto.getIsCollection());


        //3. 查询数据
        this.page(page,wrapper);

        //4. 封装分页结果返回
        PageResponseResult result = new PageResponseResult((int)page.getCurrent(),(int)page.getSize(),(int)page.getTotal());
        result.setData(page.getRecords());
        result.setCode(AppHttpCodeEnum.SUCCESS.getCode());
        result.setErrorMessage(AppHttpCodeEnum.SUCCESS.getErrorMessage());

        return result;
    }
}
